<template>
  <div class="payment-container">
    <!-- 头部信息 -->
    <el-page-header title="返回" @back="handleBack" class="header">
      <template #content>
        <div class="header-content">
          <h1>酒店预订确认</h1>
        </div>
      </template>
    </el-page-header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧内容 -->
      <div class="left-content">
        <!-- 房间图片展示 -->
        <el-image :src=roomlist.picture fit="fit" class="room-carousel" alt="房间图片" />
        <!-- 房间详细信息 -->
        <el-card class="room-info">
          <template #header>
            <div class="card-header">
              <span>房间详情</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="房间名称">{{ roomlist.roomName }}</el-descriptions-item>
            <el-descriptions-item label="床数量">{{ roomlist.bedNum }}张</el-descriptions-item>
            <el-descriptions-item label="有无早餐">{{ getRoomBreakfast(roomlist.breakfastFlag) }}</el-descriptions-item>
            <el-descriptions-item label="房间类型">{{ roomTypeList.roomTypeName }}</el-descriptions-item>
            <el-descriptions-item label="时间">
              <el-date-picker v-model="valueTime" type="datetimerange" range-separator="到" start-placeholder="入住时间"
                end-placeholder="离店时间" :disabled-date="disabledDate" 
                @calendar-change="calendarChange" @blur="handleBlur" />
            </el-descriptions-item>
            <el-descriptions-item label="设施" :span="2">
              <el-tag v-for="(facility, index) in roomInfo.facilities" :key="index" type="info" class="facility-tag">
                {{ facility }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 右侧支付信息 -->
      <div class="right-content">
        <el-card class="payment-info">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
            </div>
          </template>

          <el-descriptions :column="1" border>
            <el-descriptions-item label="支付账号">{{ userStoreInfo.userInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="应付金额">
              <span class="amount">¥ {{ roomlist.price }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <div class="payment-methods">
            <h3>选择支付方式</h3>
            <el-radio-group v-model="orderData.payMethod">
              <el-radio :label="1" class="payment-option">
                <div class="payment-content">
                  <el-image class="payment-icon" src="../pic/wechat.svg"></el-image>
                  <span>微信支付</span>
                </div>
              </el-radio>
              <el-radio :label="2" class="payment-option">
                <div class="payment-content">
                  <el-image class="payment-icon" src="../pic/alipay.svg"></el-image>
                  <span>支付宝支付</span>
                </div>
              </el-radio>
            </el-radio-group>
          </div>

          <div class="actions">
            <el-button type="primary" size="large" @click="postOrder" class="pay-button">
              立即支付
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { userStore } from '@/stores/userInfoStore.js';
import dayjs from 'dayjs';

const route = useRoute()
const router = useRouter()
const userStoreInfo = userStore();

const roomlist = ref([]) as any;

//#region 房间信息展示

// 房间信息
const roomData = ref({
  id: route.query.id, // 唯一标识
  roomName: null, // 房间名
  picture: null, // 房间图片地址
  price: null, // 售价
  roomType: null, // 房间种类
  roomStatus: null, // 房间状态（1空房，2满房，3清理中，4维修中）
  bedNum: null, // 床数量
  hourRoomFlag: null, // 是否可以作为钟点房出售（1是，0否）
  breakfastFlag: null, // 是否提供早餐（1是，0否）

  createTime: null,
  updateTime: null,

  minPrice: null,
  maxPrice: null,
});


// 获取房间信息
const fetchRoomDetail = async () => {
  try {
    const res = await api.getRoomInCondition(roomData.value);
    if (res.data.code === 1) {
      roomlist.value = res.data.data.list[0] || {};
      console.log('获取房间信息成功:', roomlist.value);
    } else {
      ElMessage.error(res.data.message || '获取房间信息失败');
    }
  } catch (error) {
    ElMessage.error('网络请求异常');
    console.error('获取房间详情失败:', error);
  }
};

const roomInfo = reactive({
  maxGuests: 3,
  facilities: ['免费WiFi', '智能马桶', '海景阳台', '迷你吧', '保险箱']
})


// 获取房间类型信息
const roomTypeData = ref({
  id: roomData.value.id,
  roomTypeName: null,
  introduction: null,
});

const roomTypeList = ref([]) as any;
const fetchRoomType = async () => {
  await api.findRoomTypeInCondition(roomTypeData.value).then((res) => {
    roomTypeList.value = res.data.data.list[0] || {};
    // console.log("房型具体类型", roomTypeList.value);
  }).catch((error) => {
    ElMessage.error('房间类型信息请求异常');
  });
};

const getRoomBreakfast = (status) => {
  if (status) {
    return '提供早餐';
  } else {
    return '不提供早餐';
  }
};
//#endregion



//#region 时间选择
const valueTime = ref(null);
const choiceDate = ref(null);

const disabledDate = (time) => {

  // 禁用今天之前的日期
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 去掉时分秒毫秒
  if (time.getTime() < today.getTime()) return true;

  // 禁用两个月后的日期
  const twoMonthsLater = new Date();
  twoMonthsLater.setMonth(twoMonthsLater.getMonth() + 2);
  if (time.getTime() > twoMonthsLater.getTime()) return true;

  // 如果已经选择了一个日期，则限制最多只能连续选择7天
  if (choiceDate.value) {
    const selectedDate = new Date(choiceDate.value);
    const timeValue = time.getTime();
    const selectedTime = selectedDate.getTime();
    const sevenDaysInMs = 7 * 24 * 60 * 60 * 1000;

    return timeValue > selectedTime + sevenDaysInMs ||
      timeValue < selectedTime - sevenDaysInMs;
  }


  return false;
};

const tempSelectedDates = ref<[Date, Date] | []>([]); // 临时存储选择的日期

const calendarChange = (obj) => {
  const minDate = obj[0];
  const maxDate = obj[1];
  choiceDate.value = minDate.getTime();
  if (maxDate) choiceDate.value = null;
  tempSelectedDates.value = obj;
};


const handleBlur = () => {
  // 确保有值且是包含两个日期的数组
  if (!tempSelectedDates.value || tempSelectedDates.value.length !== 2) {
    valueTime.value = null; // 清空不完整的选择
    return;
  }

  // 确保两个日期都是有效的Date对象
  if (!(tempSelectedDates.value[0] instanceof Date) || 
      !(tempSelectedDates.value[1] instanceof Date)) {
    valueTime.value = null;
    return;
  }

  // 复制日期对象避免污染原始数据
  const checkIn = new Date(tempSelectedDates.value[0]);
  const checkOut = new Date(tempSelectedDates.value[1]);

  // 设置固定时间
  checkIn.setHours(14, 0, 0, 0);
  checkOut.setHours(12, 0, 0, 0);

  // 确保离店日期至少比入住日期晚一天
  if (checkOut.getTime() <= checkIn.getTime()) {
    checkOut.setDate(checkIn.getDate() + 1);
    checkOut.setHours(12, 0, 0, 0);
  }

  valueTime.value = [checkIn, checkOut];
};

//#endregion



//#region 提交订单

const orderData = ref({
  id: null, // 唯一标识
  userId: null, // 付款用户id
  userAccountNumber: null, // 付款用户的账号
  checkedRoom: null, // 下单的客房id
  amount: null, // 实付金额
  payMethod: null, // 支付方式（1微信支付，2支付宝支付）
  status: null, // 订单状态（1待支付；2已付款,等待入住；3已取消；4入住中；5已完成；6已退款）
  scheduledCheckinTime: null, // 预定的入住时间
  actualCheckinTime: null, // 实际入住时间
  scheduledCheckoutTime: null, // 预定的离店时间
  actualCheckoutTime: null, // 实际离店时间
});

const updateOrder = async () => {
  // console.log("时间信息",);
  // console.log("用户id", userStoreInfo.userInfo.id);
  // console.log("用户账号", userStoreInfo.userInfo.userAccountNumber);
  // console.log("房间id", roomData.value.id);
  // console.log("房间价格", roomlist.value.price);
  // console.log("支付方式", orderData.value.payMethod);
  // console.log('第一个日期类型:', valueTime.value[0]);
  // console.log('第二个日期类型:', valueTime.value[1]);

  orderData.value.userId = userStoreInfo.userInfo.id;
  orderData.value.userAccountNumber = userStoreInfo.userInfo.userAccountNumber;
  orderData.value.checkedRoom = roomData.value.id;
  orderData.value.amount = roomlist.value.price;
  orderData.value.status = 1;
  orderData.value.scheduledCheckinTime = dayjs(valueTime.value[0]).format('YYYY-MM-DD HH:mm:ss');
  orderData.value.scheduledCheckoutTime = dayjs(valueTime.value[1]).format('YYYY-MM-DD HH:mm:ss');
}

const postOrder = async () => {

  if (!valueTime.value || !Array.isArray(valueTime.value) || valueTime.value.length !== 2) {
    ElMessage.error('请选择完整的入住和离店时间');
    return;
  }


  if (!orderData.value.payMethod) {
    ElMessage.error('请选择支付方式')
    return
  }

  
  try {
    await ElMessageBox.confirm(
      '请确认订单信息是否正确？',
      '订单确认',
      {
        confirmButtonText: '确认下单',
        cancelButtonText: '再检查一下',
        type: 'warning'
      }
    );
    
    updateOrder();
    console.log("下单信息", orderData.value);
    
    const res = await api.addOrder(orderData.value);
    ElMessage.success('正在跳转支付页面');
    router.push('/payment-success');
    
  } catch (error) {
    // 用户点击取消或关闭对话框
    if (error !== 'cancel') {
      ElMessage.error('下单失败');
    }
  }

}
//#endregion

onMounted(async () => {
  await fetchRoomDetail();
  await fetchRoomType();
});

const handleBack = () => {
  router.go(-1)
}

</script>

<style scoped>
.payment-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.payment-container .header {
  margin-bottom: 40px;
}

.payment-container .header h1 {
  margin: 20px 0;
  font-size: 24px;
  color: #333;
}

.payment-container .main-content {
  display: flex;
  gap: 30px;
}

.payment-container .main-content .left-content {
  flex: 1;
  min-width: 800px;
}

.payment-container .main-content .left-content .room-carousel {
  height: 500px;
  width: 900px;
  /* object-fit: cover; */
  border-radius: 8px;
  overflow: hidden;
}

.payment-container .main-content .left-content .room-info {
  margin-top: 20px;
}

.payment-container .main-content .left-content .room-info .facility-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.payment-container .main-content .right-content {
  width: 400px;
}

.payment-container .main-content .right-content .payment-info .amount {
  color: #ff5722;
  font-size: 24px;
  font-weight: bold;
}

.payment-container .main-content .right-content .payment-info .payment-methods {
  margin: 20px 0;
}

.payment-container .main-content .right-content .payment-info .payment-methods h3 {
  margin-bottom: 15px;
}

.payment-container .main-content .right-content .payment-info .payment-methods .payment-option {
  width: 100%;
  height: 80px;
  margin: 10px 0;
}

.payment-container .main-content .right-content .payment-info .payment-methods .payment-option .payment-content {
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.payment-container .main-content .right-content .payment-info .payment-methods .payment-option .payment-content .payment-icon {
  height: 50px;
  width: 50px;
  font-size: 40px;
  margin-right: 15px;
}

.payment-container .main-content .right-content .payment-info .actions {
  text-align: center;
  margin-top: 30px;
}

.payment-container .main-content .right-content .payment-info .actions .pay-button {
  width: 100%;
  height: 50px;
  font-size: 18px;
}

.datetime-picker-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}

@media (max-width: 1200px) {
  .payment-container .main-content {
    flex-direction: column;
  }

  .payment-container .main-content .left-content {
    min-width: auto !important;
  }

  .payment-container .main-content .right-content {
    width: auto !important;
  }
}
</style>